<template>
    <!-- 测量点弹窗 -->
    <a-modal v-bind="$attrs" v-on="$listeners" :visible.sync="dialogVisible" @cancel="handleCancel">
      <b slot="title">{{ headerTitle }}</b>
      <a-spin :spinning="submitLoading">
        <a-row :gutter="10" class="mb12">
          <a-col :span="10">
            <a-tree-select
              v-model="valueLeft"
              tree-checkable
              :tree-data="treeDataLeft"
              placeholder="请选择"
              style="width: 100%"
              allow-clear
              showSearch
              :treeCheckStrictly="true"
              :replaceFields="{ children: 'children', title: 'name', key: 'id', value: 'id' }"
              @change="onLeftChange"
            >
            </a-tree-select>
          </a-col>
          <a-col :span="2" style="text-align: center;line-height: 30px;">继承</a-col>
          <a-col :span="10">
            <a-tree-select
              v-model="valueRight"
              :tree-data="treeDataRight"
              placeholder="请选择"
              style="width: 100%"
              allow-clear
              showSearch
              :treeCheckStrictly="true"
              :replaceFields="{ children: 'children', title: 'name', key: 'id', value: 'id' }"
              @select="onRightSelect"
            >
            </a-tree-select>
          </a-col>
        </a-row>
        <div class="mb12">
          <span>选择需继承点位名称：</span>
          <a-button type="primary" @click="selectAll">全部选中</a-button>
          <a-button style="margin-left: 20px" @click="selectAllNot">取消全选</a-button>
        </div>
        <!-- 表格 -->
        <a-spin :spinning="tabLoading">
          <s-table
            ref="table"
            tableLayout="fixed"
            size="default"
            :rowKey="(row) => row.mapId"
            :columns="columns"
            :row-selection="rowSelection"
            :data="loadData"
            :alert="true"
            :isCurrentChangeClearSelectedRow="false"
            bordered
            show-size-changer
            show-quick-jumper
            showPagination="auto"
          >
          </s-table>
        </a-spin>
      </a-spin>
      <!-- 页脚操作栏 -->
      <div slot="footer" class="btn_box">
        <a-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</a-button>
        <a-button style="margin-left: 20px;" @click="handleCancel">关闭</a-button>
      </div>
    </a-modal>
  </template>
  
  <script>
  import { map } from '@/api/quality/reality' // 通用api
  import { STable } from '@/components' // 表格
  export default {
    name:'DialogChoose',
    components: {
      STable,
    },
    props: {
      projectId: {
        type: String,
        default() {
          return ''
        },
      },
      // 显隐控件
      visible: {
        type: Boolean,
        default() {
          return false
        },
      },
      // 详情
      outsideTreeList: {
        type: Array,
        default() {
          return () => []
        },
      },
      // 标题
      headerTitle: {
        type: String,
        default() {
          return ''
        },
      },
    },
    computed: {
      // 与父组件绑定visible
      dialogVisible: {
        get: function () {
          return this.visible
        },
        set: function (e) {
          this.$emit('update:visible', e)
        },
      },
      rowSelection() {
        return {
          selectedRowKeys: this.selectedRowKeys,
          onChange: this.handleSelectedChanged,
        }
      }
    },
    data() {
      return {
        valueLeft: [],
        valueRight: '',
        treeDataLeft: [],
        treeDataRight: [],
        tabLoading: false,
        allData: [],
        respAreaNodeId: '',
        nodeIds: [],
        pointIds: [],
        submitLoading: false,
        selectedRowKeys: [],
        loadData: (parameter) => {
          return this.resoveData(parameter).then((res) => {
            return res
          })
        },
        columns: [
          {
            title: '点位名称',
            ellipsis: true,
            dataIndex: 'pointName',
            width: '130px',
          },
          {
            title: '点位等级',
            dataIndex: 'belong',
            ellipsis: true,
            width: '130px',
          },
          {
            title: '检查项数量',
            dataIndex: 'checkItemNumber',
            width: '130px',
          },
          {
            title: '点位描述',
            ellipsis: true,
            dataIndex: 'pointDescription',
          }
        ],
      }
    },
    methods: {
      /**
       * 选中数据变化
       * @param {Array} selectedRowKeys - 所有已选行的key
       * @param {Array} selectedRows - 所有已选行
       */
      handleSelectedChanged(selectedRowKeys, selectedRows) {
        this.selectedRowKeys = selectedRowKeys
      },
      resoveData(parameter) {
        return new Promise(resolve => {
          const pageNo = parameter.pageNo
          const pageSize = parameter.pageSize
          const data = this.allData.filter((item,index) => 
              pageSize * (pageNo -1) <= index &&  
              index < pageSize * pageNo
          )
          const res = {
            currentPage: pageNo,
            totalPage: Math.ceil(this.allData.length / pageSize),
            totalSize: this.allData.length,
            pageSize: pageSize,
            data,
            code: 200,
            message: "success",
            success: true
          }
          resolve(res)
        }) 
      },
      getDetail() {
        this.tabLoading = true
        map.postDetail({ isView: 0,respAreaNodeId: this.respAreaNodeId, queryType: '1' })
          .then((res) => {
            this.tabLoading = false
            if (res.code === 200) {
              if (res.data && res.data.mapPoints && res.data.mapPoints.length > 0) {
                const actualType = {
                  '0': '公司级别',
                  '1': '分公司级别',
                  '2': '项目级别',
                }
                this.allData = res.data.mapPoints.map(item => {
                  const json = {
                    pointName: item.pointName,
                    // belong: actualType[item.actualType],
                    belong: item?.pointTypeNodeVO?.nodeLevel?.name,
                    checkItemNumber: item.checkItems ? item.checkItems.length : 0,
                    pointDescription: item.pointDescription,
                    mapId: item.mapId
                  };
                  return json
                })
                this.$refs.table.refresh(true)
              } else {
                this.allData = []
                this.$refs.table.refresh(true)
              }
            }
          }
        )
      },
      handleCancel() {
        this.dialogVisible = false
      },
      onLeftChange(value, node, extra) {
        this.nodeIds = value.map(item => item.value)
      },
      onRightSelect(value, node, extra) {
        this.respAreaNodeId = value
        this.getDetail()
      },
      deepFindCheck(allList) {
        const deepArr = (arr) => {
          for(let i = 0;i<arr.length; i++) {
            if (!!!arr[i].parentId) {
              // 所有节点不可选
              arr[i].disabled = true
            } else {
              arr[i].disabled = arr[i].check
            }
            if (arr[i].children && arr[i].children.length > 0) {
              deepArr(arr[i].children)
            }
          }
        }
        deepArr(allList)
        return allList
      },
      selectAll() {
        const selectedRowKeys = this.allData.map(item => item.mapId)
        this.$refs.table.updateSelect(selectedRowKeys, this.allData)
        this.selectedRowKeys = selectedRowKeys
      },
      selectAllNot() {
        this.selectedRowKeys = []
        this.$refs.table.clearSelected()
      },
      handleSubmit() {
        // nodeIds 继承节点
        // nodeId 被继承节点
        if (!this.respAreaNodeId) {
          this.$message.warning('请选择被继承节点！')
          return false
        }
        if (this.selectedRowKeys.length === 0 ) {
          this.$message.warning('请选择需继承点位！')
          return false
        }
        if (this.nodeIds.length === 0 ) {
          this.$message.warning('请选择继承节点！')
          return false
        }
        const isAll = this.selectedRowKeys.length === this.allData.length
        const pointIds = this.selectedRowKeys
        this.submitLoading = true
        map.postInherit({isAll, nodeIds: this.nodeIds, nodeId: this.respAreaNodeId, pointIds, projectId: this.projectId}).then(res => {
          if (res.data && res.data.code === 200) {
            this.$message.warning('提交成功！')
            this.$emit('submitInherit')
          }
          this.submitLoading = false
        }).catch(() => {
          this.submitLoading = false
        })
      }
    },
    watch: {
      visible(e) {
        if (e) {
          this.$nextTick(() => {
            // 清空数据
            this.valueLeft = []
            this.valueRight = ''
            this.allData = []
            this.$refs.table.refresh(true)
            this.selectAllNot()
          })
        }
      },
      outsideTreeList: {
        immediate: true,
        deep: true,
        handler(val) {
          if (val) {
            let temp1 = this.$clone(val)
            let temp2 = this.$clone(val)
            if (temp2 && temp2.length > 0) {
              for(let i = 0;i<temp2.length; i++) {
                if (!!!temp2[i].parentId) {
                  // 所有节点不可选
                  temp2[i].disabled = true
                }
              }
            }
            this.treeDataLeft = this.deepFindCheck(temp1)
            this.treeDataRight = temp2
          }
        }
      },
    },
  }
  </script>
  